Learn C in 10 minutes
C is a powerful, general-purpose programming language known for its efficiency and close-to-hardware capabilities. This tutorial covers the fundamentals of C programming, helping you quickly understand the language.
1. Writing Your First C Program
Let’s start with the classic “Hello, World!” program. Create a file named hello.c
and enter the following code:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Save the file and compile it using a C compiler like GCC:
gcc hello.c -o hello
./hello
The output will be:
Hello, World!
This simple program demonstrates C’s basic structure:
#include <stdio.h>
includes the standard input/output libraryint main()
is the program’s entry pointprintf()
displays text outputreturn 0
indicates successful execution
2. Basic Syntax
C uses a structured syntax with semicolons to terminate statements and curly braces {}
to define code blocks.
// This is a single-line comment
/* This is a multi-line comment */
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Basic syntax rules in C:
- Semicolons: Every statement must end with a semicolon
;
- Comments: Single-line comments use
//
, multi-line comments use/* */
- Code Blocks: Defined by curly braces
{}
- Case Sensitivity: C is case-sensitive (
main
vsMain
)
3. Variables and Data Types
C is a statically typed language, meaning you must declare variable types before use.
Basic variable naming rules:
- Variable names can contain letters, numbers, and underscores
- Variable names cannot start with a number
- Variable names are case-sensitive
- C keywords cannot be used as variable names
C’s main data types:
- int: Integer numbers (e.g.,
42
,-10
) - float: Floating-point numbers (e.g.,
3.14
,-2.5
) - double: Double-precision floating-point numbers
- char: Single characters (e.g.,
'A'
,'z'
) - void: No type
int age = 25;
float temperature = 36.5;
double pi = 3.14159265359;
char grade = 'A';
3.1 Integer Types
C provides several integer types with different sizes:
char small_number = 100; // Usually 1 byte
short medium_number = 32000; // Usually 2 bytes
int regular_number = 1000000; // Usually 4 bytes
long large_number = 1000000000; // Usually 4 or 8 bytes
3.2 Floating-Point Types
float single_precision = 3.14f;
double double_precision = 3.14159265359;
long double extended_precision = 3.14159265358979323846L;
3.3 Character Type
Characters are stored as integers using ASCII encoding:
char letter = 'A';
char digit = '7';
char newline = '\n';
char tab = '\t';
4. Constants
Constants are fixed values that cannot be changed during program execution:
const int MAX_SIZE = 100;
const float PI = 3.14159;
const char NEWLINE = '\n';
#define MAX_USERS 1000
#define PI 3.14159
5. Input and Output
C uses functions from stdio.h
for input and output operations.
5.1 Output with printf()
#include <stdio.h>
int main() {
int age = 25;
float height = 1.75;
char name[] = "John";
printf("Hello, %s!\n", name);
printf("You are %d years old\n", age);
printf("Your height is %.2f meters\n", height);
return 0;
}
Common format specifiers:
%d
- integer%f
- float/double%c
- character%s
- string%p
- pointer
5.2 Input with scanf()
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height: ");
scanf("%f", &height);
printf("Hello %s, you are %d years old and %.2f meters tall\n",
name, age, height);
return 0;
}
6. Operators
C provides a rich set of operators for various computations.
6.1 Arithmetic Operators
int a = 10, b = 3;
printf("Addition: %d\n", a + b); // 13
printf("Subtraction: %d\n", a - b); // 7
printf("Multiplication: %d\n", a * b); // 30
printf("Division: %d\n", a / b); // 3
printf("Modulus: %d\n", a % b); // 1
6.2 Comparison Operators
int x = 5, y = 10;
printf("Equal: %d\n", x == y); // 0 (false)
printf("Not equal: %d\n", x != y); // 1 (true)
printf("Greater than: %d\n", x > y); // 0
printf("Less than: %d\n", x < y); // 1
6.3 Logical Operators
int a = 1, b = 0;
printf("AND: %d\n", a && b); // 0
printf("OR: %d\n", a || b); // 1
printf("NOT: %d\n", !a); // 0
6.4 Bitwise Operators
unsigned int a = 5; // 0101 in binary
unsigned int b = 3; // 0011 in binary
printf("AND: %d\n", a & b); // 1 (0001)
printf("OR: %d\n", a | b); // 7 (0111)
printf("XOR: %d\n", a ^ b); // 6 (0110)
printf("NOT: %d\n", ~a); // depends on system
printf("Left shift: %d\n", a << 1); // 10 (1010)
printf("Right shift: %d\n", a >> 1); // 2 (0010)
7. Control Flow
C provides several control flow statements to manage program execution.
7.1 if Statements
int age = 20;
if (age >= 18) {
printf("Adult\n");
} else if (age >= 13) {
printf("Teen\n");
} else {
printf("Child\n");
}
7.2 switch Statements
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Other day\n");
}
7.3 for Loops
for (int i = 0; i < 5; i++) {
printf("i = %d\n", i);
}
7.4 while Loops
int count = 0;
while (count < 5) {
printf("Count: %d\n", count);
count++;
}
7.5 do-while Loops
int count = 0;
do {
printf("Count: %d\n", count);
count++;
} while (count < 5);
7.6 break and continue
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("i = %d\n", i); // Output: 1, 3
}
8. Arrays
Arrays store multiple values of the same type.
8.1 One-dimensional Arrays
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing elements
printf("First element: %d\n", numbers[0]);
printf("Last element: %d\n", numbers[4]);
// Modifying elements
numbers[0] = 10;
// Looping through array
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
8.2 Multi-dimensional Arrays
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Accessing elements
printf("matrix[1][2] = %d\n", matrix[1][2]); // 6
// Looping through 2D array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
9. Strings
In C, strings are arrays of characters terminated by a null character \0
.
char greeting[] = "Hello"; // Automatically includes null terminator
char name[20] = "John";
// String functions from string.h
#include <string.h>
char str1[20] = "Hello";
char str2[20] = "World";
printf("Length: %lu\n", strlen(str1)); // 5
strcpy(str1, str2); // Copy str2 to str1
printf("After copy: %s\n", str1); // World
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
}
10. Functions
Functions are reusable blocks of code that perform specific tasks.
10.1 Function Definition and Calling
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3);
printf("5 + 3 = %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
10.2 Function with No Return Value
void greet(char name[]) {
printf("Hello, %s!\n", name);
}
int main() {
greet("Alice");
return 0;
}
10.3 Recursive Functions
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
printf("5! = %d\n", factorial(5)); // 120
return 0;
}
11. Pointers
Pointers are variables that store memory addresses.
11.1 Basic Pointer Usage
int number = 42;
int *ptr = &number; // ptr stores address of number
printf("Value: %d\n", number); // 42
printf("Address: %p\n", &number); // Memory address
printf("Pointer value: %d\n", *ptr); // 42 (dereferencing)
// Modifying value through pointer
*ptr = 100;
printf("New value: %d\n", number); // 100
11.2 Pointers and Arrays
int numbers[] = {1, 2, 3, 4, 5};
int *ptr = numbers; // points to first element
printf("First element: %d\n", *ptr); // 1
printf("Second element: %d\n", *(ptr + 1)); // 2
// Array name is essentially a pointer to first element
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, *(numbers + i));
}
11.3 Pointers and Functions
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x=%d, y=%d\n", x, y);
swap(&x, &y);
printf("After swap: x=%d, y=%d\n", x, y);
return 0;
}
12. Structures
Structures allow you to group related variables together.
12.1 Defining and Using Structures
#include <stdio.h>
#include <string.h>
// Structure definition
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
// Creating structure variables
struct Student student1;
// Assigning values
strcpy(student1.name, "Alice");
student1.age = 20;
student1.gpa = 3.8;
// Accessing structure members
printf("Name: %s\n", student1.name);
printf("Age: %d\n", student1.age);
printf("GPA: %.2f\n", student1.gpa);
return 0;
}
12.2 Structure with Pointers
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {10, 20};
struct Point *ptr = &p1;
printf("Coordinates: (%d, %d)\n", ptr->x, ptr->y);
return 0;
}
13. Dynamic Memory Allocation
C provides functions for dynamic memory management.
13.1 malloc, calloc, realloc, free
#include <stdio.h>
#include <stdlib.h>
int main() {
// Allocate memory for 5 integers
int *numbers = (int*)malloc(5 * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Initialize array
for (int i = 0; i < 5; i++) {
numbers[i] = i * 10;
}
// Print array
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
// Free allocated memory
free(numbers);
return 0;
}
13.2 Dynamic String Allocation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *name = (char*)malloc(50 * sizeof(char));
if (name != NULL) {
strcpy(name, "Dynamic string");
printf("Name: %s\n", name);
free(name);
}
return 0;
}
14. File Operations
C provides functions for reading from and writing to files.
14.1 Writing to a File
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, File!\n");
fprintf(file, "This is a test.\n");
fclose(file);
printf("File written successfully.\n");
return 0;
}
14.2 Reading from a File
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}
15. Preprocessor Directives
Preprocessor directives are processed before compilation.
15.1 #include
#include <stdio.h> // System header file
#include "myheader.h" // User header file
15.2 #define
#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main() {
double area = PI * 5 * 5;
int larger = MAX(10, 20);
printf("Area: %.2f\n", area);
printf("Larger number: %d\n", larger);
return 0;
}
15.3 Conditional Compilation
#define DEBUG 1
int main() {
#ifdef DEBUG
printf("Debug mode enabled\n");
#endif
#if DEBUG == 1
printf("Debug level 1\n");
#elif DEBUG == 2
printf("Debug level 2\n");
#else
printf("No debug\n");
#endif
return 0;
}
16. Error Handling
C doesn’t have built-in exception handling, so we use return values and error codes.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
printf("Error opening file: %s\n", strerror(errno));
return 1;
}
fclose(file);
return 0;
}
This comprehensive C tutorial covers the essential concepts you need to start programming in C. Practice these examples and explore more advanced topics like linked lists, function pointers, and multi-file programs as you become more comfortable with the language.